// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env:'cloud1-7gb9s3y025614beb'
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const studentCollection = db.collection('pc_student')
  let openid = wxContext.OPENID
  let {sn,name,nickName,avatarUrl} = event
  
console.log(sn,name,nickName,avatarUrl)

let res = await studentCollection.where({
  sn,name
}).get()
console.log(res)
let user = {}
let reg = 'ok'
let errMsg = ''

if(res.data.length==0){
  reg = 'err'
  errMsg = '没找打匹配的学号姓名'
}else{
  if(res.data[0].avatarUrl){
    reg = 'err'
    errMsg = '学号:'+sn+'已经被微信名称'+res.data[0].nickName+'绑定'
  }else{
        user = {...res.data[0],nickName,avatarUrl,openid}
        res = await studentCollection.doc(res.data[0]._id).update({
          data:{
            nickName,avatarUrl,openid
          }
        })
  }
}
  return {
   reg,errMsg,user
  }
}